package com.springcloud.alibaba.consumer.lib;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author:RenPu
 * @Date: 2020/6/30 13:39
 * @Version: 1.0
 * @description: cas+自旋锁实现轮旋算法
 */

@Component
public class MyLoadBananceImpl implements LoadBalance {


    //创建原子对象
    private AtomicInteger atomicInteger=new AtomicInteger(0);

    public final int getAndIncrement(){

        int current;
        int next;
        do{
            current=this.atomicInteger.get();
            //2147483647的值为AtomicInteger的最大值
            next=current>=2147483647?0:current+1;
        }while (!this.atomicInteger.compareAndSet(current,next));

        System.out.println("******第几次访问，次数next:"+next);

        return next;



    }


    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {

        //请求的次数除以集群数求模数，作为分发给第几台机器的下标
        int index=getAndIncrement()%serviceInstances.size();
        return serviceInstances.get(index);
    }
}
